package com.dudu.common.util

import android.view.Gravity
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.transition.Slide.GravityFlag
import com.dudu.common.R

/**
 * <pre>
 *     author : dzc
 *     time   : 2024/10/31
 *     desc   : 自定义Toast样式， 版本>=Android R(30)，gravity和setView无效或失效
 * </pre>
 */
object ToastUtils {

    @LayoutRes
    var layout: Int = R.layout.view_toast

    @GravityFlag
    var gravity: Int = Gravity.TOP

    var duration: Int = Toast.LENGTH_LONG

    private var toast: Toast? = null

    fun show(msg: String){

        toast?.cancel()

        toast = Toast(applicationContext)
        val layoutView = LayoutInflater.from(applicationContext).inflate(layout, null)
        toast?.setGravity(gravity, 0, 0)
        toast?.duration = duration
        toast?.view = layoutView

        toast?.let {
            val toastText: TextView? = layoutView?.findViewWithTag<TextView>("toast_text")
            toastText?.text = msg
            it.show()
        }
    }

}